<template>
  <a-card>
    <template #title>
      <a-button type="primary" @click="addList" v-permiss="['add']">添加</a-button>
    </template>
    <a-table row-key="id" :columns="tableColumn" :pagination="pagination" :data-source="tableData">
      <template #operation="{record}">
        <a-button type="link" @click="editList(record)" v-permiss="['update']">修改</a-button>
      </template>
    </a-table>

    <a-modal v-model:visible="visible.isShow" :title="visible.title" @ok="confirm"
             :afterClose="clearForm"
             width="70%"
             :maskClosable="false">
      <div style="margin-bottom: 10px">
        <a-month-picker style="width:220px" v-model:value="form.month" valueFormat="YYYY-MM" placeholder="请选择月份"
                        format="YYYY-MM"/>
        <div style="margin-top: 15px;display:flex">
          <a-upload
              accept=".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              name="file"
              :showUploadList="false"
              :before-upload="excelFileUpload"
          >
            <a-button type="primary" style="margin-right: 15px">
              <upload-outlined></upload-outlined>
              导入
            </a-button>
          </a-upload>
          <a-button><a href="https://ddhkapps.oss-cn-hongkong.aliyuncs.com/doc/analysis_temp.xlsx">下载模板</a></a-button>
        </div>
      </div>
      <a-table row-key="value" :columns="addTableColumn" bordered :pagination="false" :data-source="addTableData">
        <template #title="{record}">
          <div v-html="record ?  record.title : ''"></div>
        </template>
        <template #value="{record,index}">
          <a-input style="width:100%" @change="changeValueComputed(index)" v-model:value="form[record.value]"/>
        </template>
      </a-table>
    </a-modal>
  </a-card>
</template>

<script>
import {ref, onMounted, reactive, computed, toRefs, h} from 'vue'
import {
  importProfitAnalysis,
  increaseProfitAnalysis,
  fetchProfitAnalysisList,
  updateProfitAnalysis
} from '../../../api/finance'
import {message} from "ant-design-vue";
import XLSX from "xlsx"
import {UploadOutlined} from "@ant-design/icons-vue";

const tableColumn = [
  {title: '日期', dataIndex: 'month', width: 150, align: 'center'},
  {title: '更新时间', dataIndex: 'updateTime', width: 150, align: 'center'},
  {title: '操作', width: 100, align: 'center', slots: {customRender: 'operation',}},
]

const addTableData = [
  {oneTitle: '业务情况', twoTitle: '业务利润', threeTitle: '-', value: 'businessProfit'},
  {oneTitle: '业务情况', twoTitle: '经营利润', threeTitle: '-', value: 'netProfit'},
  {oneTitle: '业务情况', twoTitle: '合同金额', threeTitle: '-', value: 'contractAmount'},
  {oneTitle: '业务情况', twoTitle: '新客合同金额', threeTitle: '-', value: 'contractAmountNew'},
  {oneTitle: '业务情况', twoTitle: '老客合同金额', threeTitle: '-', value: 'contractAmountOld'},
  {oneTitle: '业务情况', twoTitle: '放款本金', threeTitle: '-', value: 'loanPrincipal'},
  {oneTitle: '业务情况', twoTitle: '回款本金', threeTitle: '-', value: 'paymentPrincipal'},
  {oneTitle: '业务情况', twoTitle: '放款订单量', threeTitle: '-', value: 'loanOrderCount'},
  {oneTitle: '业务情况', twoTitle: '新客放款订单量', threeTitle: '-', value: 'loanOrderCountNew'},
  {oneTitle: '业务情况', twoTitle: '老客放款订单量', threeTitle: '-', value: 'loanOrderCountOld'},
  {oneTitle: '业务情况', twoTitle: '还款订单量', threeTitle: '-', value: 'returnedOrderCount'},
  {oneTitle: '业务情况', twoTitle: '新客还款订单量', threeTitle: '-', value: 'returnedOrderCountNew'},
  {oneTitle: '业务情况', twoTitle: '老客还款订单量', threeTitle: '-', value: 'returnedOrderCountOld'},
  {oneTitle: '业务情况', twoTitle: '还款率', threeTitle: '-', value: 'repaymentRate'},
  {oneTitle: '业务情况', twoTitle: '新客还款率', threeTitle: '-', value: 'newRepaymentRate'},
  {oneTitle: '业务情况', twoTitle: '老客还款率', threeTitle: '-', value: 'oldRepaymentRate'},
  {oneTitle: '业务情况', twoTitle: '件均', threeTitle: '-', value: 'orderAverageContractAmount'},
  {oneTitle: '业务情况', twoTitle: '新客件均', threeTitle: '-', value: 'newOrderAverageContractAmount'},
  {oneTitle: '业务情况', twoTitle: '老客件均', threeTitle: '-', value: 'oldOrderAverageContractAmount'},
  {oneTitle: '业务情况', twoTitle: '合同金额首逾', threeTitle: '-', value: 'firstExcessOfContractAmount'},
  {oneTitle: '业务情况', twoTitle: '新客合同金额首逾', threeTitle: '-', value: 'firstExcessOfContractAmountNew'},
  {oneTitle: '业务情况', twoTitle: '老客合同金额首逾', threeTitle: '-', value: 'firstExcessOfContractAmountOld'},
  {oneTitle: '业务情况', twoTitle: '合同金额首逾率 [= 合同金额首逾数 / 合同金额]', threeTitle: '-', value: 'firstOverRateOfContractAmount'},
  {oneTitle: '业务情况', twoTitle: '新客合同金额首逾率', threeTitle: '-', value: 'newFirstOverRateOfContractAmount'},
  {oneTitle: '业务情况', twoTitle: '老客合同金额首逾率', threeTitle: '-', value: 'oldFirstOverRateOfContractAmount'},
  {oneTitle: '业务情况', twoTitle: '合同金额M1催回数', threeTitle: '-', value: 'contractAmountM1NumberOfReminders'},
  {
    oneTitle: '业务情况',
    twoTitle: '合同金额M1催回率 [= 合同金额M1催回数 / 合同金额首逾数]',
    threeTitle: '-',
    value: 'contractAmountM1RateOfReminders'
  },
  {oneTitle: '收入组成', twoTitle: '收入合计 [= 主营业务收入+其他业务收入+营业外收入]', threeTitle: '-', value: 'totalRevenue'},
  {oneTitle: '收入组成', twoTitle: '主营业务收入合计', threeTitle: '主营业务收入合计', value: 'totalMainBusinessIncome'},
  {oneTitle: '收入组成', twoTitle: '主营业务收入合计', threeTitle: '利息收入', value: 'interestIncome'},
  {oneTitle: '收入组成', twoTitle: '主营业务收入合计', threeTitle: '罚息收入', value: 'penaltyInterestIncome'},
  {oneTitle: '收入组成', twoTitle: '主营业务收入合计', threeTitle: '手续费收入', value: 'commissionIncome'},
  {oneTitle: '收入组成', twoTitle: '主营业务收入合计', threeTitle: '展期手续费收入', value: 'incomeFromExtension'},
  {oneTitle: '收入组成', twoTitle: '主营业务收入合计', threeTitle: '历史逾期收入', value: 'historicalOverdueIncome'},
  {oneTitle: '收入组成', twoTitle: '主营业务收入合计', threeTitle: '业务额外收入', value: 'additionalBusinessIncome'},
  {oneTitle: '收入组成', twoTitle: '其他业务收入', threeTitle: '-', value: 'otherBusinessIncome'},
  {oneTitle: '收入组成', twoTitle: '营业外收入', threeTitle: '-', value: 'nonOperatingIncome'},


  {oneTitle: '支出组成', twoTitle: '支出合计 [= 主营业务成本 + 费用合计 + 资产减值损失合计 +营业外支出]', threeTitle: '-', value: 'totalExpenditure'},
  {oneTitle: '支出组成', twoTitle: '主营业务成本', threeTitle: '-', value: 'costOfMainBusiness'},
  {oneTitle: '支出组成', twoTitle: '费用合计', threeTitle: '费用合计', value: 'totalCost'},
  {oneTitle: '支出组成', twoTitle: '费用合计', threeTitle: '营业费用', value: 'operatingExpenses'},
  {oneTitle: '支出组成', twoTitle: '费用合计', threeTitle: '管理费用', value: 'managementExpenses'},
  {oneTitle: '支出组成', twoTitle: '费用合计', threeTitle: '财务费用', value: 'financialExpenses'},
  {oneTitle: '支出组成', twoTitle: '资产减值损失合计', threeTitle: '资产减值损失合计', value: 'totalAssetImpairmentLoss'},
  {oneTitle: '支出组成', twoTitle: '资产减值损失合计', threeTitle: 'M1(1-7)', value: 'm1'},
  {oneTitle: '支出组成', twoTitle: '资产减值损失合计', threeTitle: 'M2(8-15)', value: 'm2'},
  {oneTitle: '支出组成', twoTitle: '资产减值损失合计', threeTitle: 'M3(16-30)', value: 'm3'},
  {oneTitle: '支出组成', twoTitle: '资产减值损失合计', threeTitle: 'M3+(30天+)', value: 'm3a'},
  {oneTitle: '支出组成', twoTitle: '资产减值损失合计', threeTitle: '展期本金', value: 'renewalPrincipal'},
  {oneTitle: '支出组成', twoTitle: '营业外支出', threeTitle: '-', value: 'nonOperatingExpenses'},
]
console.log(addTableData)
const addTableColumn = [
  {
    title: '一级科目名称', dataIndex: 'oneTitle', align: 'center', customRender: ({text, index}) => {
      const renderObj = {
        children: text,
        props: {},
      }
      if (text === '业务情况') {
        renderObj.props.rowSpan = index === 0 ? 27 : 0
      } else if (text === '收入组成') {
        renderObj.props.rowSpan = index === 27 ? 10 : 0
      } else if (text === '支出组成') {
        renderObj.props.rowSpan = index === 37 ? 13 : 0
      }

      return renderObj
    }
  },
  {
    title: '二级科目名称', dataIndex: 'twoTitle', align: 'center', customRender: ({text, index}) => {
      const renderObj = {
        children: text,
        props: {},
      }
      if (text === '主营业务收入合计') {
        renderObj.props.rowSpan = index === 28 ? 7 : 0
      } else if (text === '费用合计') {
        renderObj.props.rowSpan = index === 39 ? 4 : 0
      } else if (text === '资产减值损失合计') {
        renderObj.props.rowSpan = index === 43 ? 6 : 0
      }
      return renderObj
    }
  },
  {
    title: '三级科目名称', dataIndex: 'threeTitle', align: 'center',
  },
  {title: '参数', dataIndex: 'value', align: 'center', slots: {customRender: 'value',}},
]


export default {
  name: "BusinessAnalysisManage",
  components: {
    UploadOutlined
  },
  setup() {
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      visible: {
        isShow: false,
        title: '',
        type: ''
      },
      form: {
        month: null
      },

    })
    const pagination = computed(() => ({
      current: state.page.pageNum,
      total: state.page.total,
      pageSize: state.page.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '50', '100', '200'],
      showTotal: total => total + '条',
      onChange: (page) => {
        state.page.pageNum = page
        getTableData()
      },
      onShowSizeChange: (page, size) => {
        state.page.pageNum = page
        state.page.pageSize = size
        getTableData()
      }
    }))

    async function getTableData() {
      const businessId = sessionStorage.getItem('businessValue')
      if (!businessId) return message.error('请选择事业部')
      const res = await fetchProfitAnalysisList({
        ...state.page,
        businessId: parseInt(businessId)
      })
      if (res.code === 200) {
        const {list, total} = res.data
        state.tableData = list
        state.page.total = total
      }
    }


    function addList() {
      state.visible = {
        isShow: true,
        type: 'add',
        title: '添加'
      }
    }

    function editList(record) {
      state.form = {...record}
      state.visible = {
        isShow: true,
        type: 'update',
        title: '修改'
      }
    }

    function clearForm() {
      state.form = {
        month: null
      }
    }

    function isNaNOrInfinity(value) {
      return (value === 'NaN' || value === 'Infinity')
    }

    function changeValueComputed(index) {
      setOperatingProfit()
      setContractAmount()
      setLoanOrderCount()
      setReturnedOrderCount()
      setRepaymentRate()
      setNewRepaymentRate()
      setOldRepaymentRate()
      setOrderAverageContractAmount()
      setNewOrderAverageContractAmount()
      setOldOrderAverageContractAmount()
      setFirstExcessOfContractAmount()
      setFirstOverRateOfContractAmount()
      setNewFirstOverRateOfContractAmount()
      setOldFirstOverRateOfContractAmount()
      setContractAmountM1RateOfReminders()
      setTotalRevenue()
      if (index >= 29 && index <= 34) {
        setTotalMainBusinessIncome()
      }
      setTotalExpenditure()
      if (index >= 40 && index <= 42) {
        setTotalCost()
      }
      if (index >= 44 && index <= 48) {
        setTotalAssetImpairmentLoss()
      }
    }

    // 经营利润
    function setOperatingProfit() {
      const d29 = parseFloat(state.form[addTableData[27].value] || 0)
      const d39 = parseFloat(state.form[addTableData[37].value] || 0)
      const value = (d29 - d39).toFixed(2)
      state.form['netProfit'] = (isNaNOrInfinity(value) ? '0.00' : value)
    }

    // 合同金额
    function setContractAmount() {
      const d5 = parseFloat(state.form[addTableData[3].value] || 0)
      const d6 = parseFloat(state.form[addTableData[4].value] || 0)
      const value = (d5 + d6).toFixed(2)
      state.form['contractAmount'] = (isNaNOrInfinity(value) ? '0.00' : value)
    }

    // 放款订单量
    function setLoanOrderCount() {
      const d10 = parseFloat(state.form[addTableData[8].value] || 0)
      const d11 = parseFloat(state.form[addTableData[9].value] || 0)
      const value = (d10 + d11).toFixed(0)
      state.form['loanOrderCount'] = (isNaNOrInfinity(value) ? '0' : value)
    }

    // 还款订单量
    function setReturnedOrderCount() {
      const d13 = parseFloat(state.form[addTableData[11].value] || 0)
      const d14 = parseFloat(state.form[addTableData[12].value] || 0)
      const value = (d13 + d14).toFixed(0)
      state.form['returnedOrderCount'] = (isNaNOrInfinity(value) ? '0' : value)
    }

    // 还款率
    function setRepaymentRate() {
      const d9 = parseFloat(state.form[addTableData[7].value] || 0)
      const d12 = parseFloat(state.form[addTableData[10].value] || 0)
      const value = ((d12 / d9) * 100).toFixed(2)
      state.form['repaymentRate'] = (isNaNOrInfinity(value) ? '0.00' : value) + '%'
    }

    // 新客还款率
    function setNewRepaymentRate() {
      const d10 = parseFloat(state.form[addTableData[8].value] || 0)
      const d13 = parseFloat(state.form[addTableData[11].value] || 0)
      const value = ((d13 / d10) * 100).toFixed(2)
      state.form['newRepaymentRate'] = (isNaNOrInfinity(value) ? '0.00' : value) + '%'
    }

    // 老客还款率
    function setOldRepaymentRate() {
      const d11 = parseFloat(state.form[addTableData[9].value] || 0)
      const d14 = parseFloat(state.form[addTableData[12].value] || 0)
      const value = ((d14 / d11) * 100).toFixed(2)
      state.form['oldRepaymentRate'] = (isNaNOrInfinity(value) ? '0.00' : value) + '%'
    }

    // 件均
    function setOrderAverageContractAmount() {
      const d4 = parseFloat(state.form[addTableData[2].value] || 0)
      const d9 = parseFloat(state.form[addTableData[7].value] || 0)
      const value = (d4 / d9).toFixed(2)
      state.form['orderAverageContractAmount'] = (isNaNOrInfinity(value) ? '0.00' : value)
    }

    // 新客件均
    function setNewOrderAverageContractAmount() {
      const d5 = parseFloat(state.form[addTableData[3].value] || 0)
      const d10 = parseFloat(state.form[addTableData[8].value] || 0)
      const value = (d5 / d10).toFixed(2)
      state.form['newOrderAverageContractAmount'] = (isNaNOrInfinity(value) ? '0.00' : value)
    }

    // 老客件均
    function setOldOrderAverageContractAmount() {
      const d6 = parseFloat(state.form[addTableData[4].value] || 0)
      const d11 = parseFloat(state.form[addTableData[9].value] || 0)
      const value = (d6 / d11).toFixed(2)
      state.form['oldOrderAverageContractAmount'] = (isNaNOrInfinity(value) ? '0.00' : value)
    }

    // 合同金额首逾数
    function setFirstExcessOfContractAmount() {
      const d22 = parseFloat(state.form[addTableData[20].value] || 0)
      const d23 = parseFloat(state.form[addTableData[21].value] || 0)
      const value = (d22 + d23).toFixed(0)
      state.form['firstExcessOfContractAmount'] = (isNaNOrInfinity(value) ? '0' : value)
    }

    // 合同金额首逾率
    function setFirstOverRateOfContractAmount() {
      const d4 = parseFloat(state.form[addTableData[2].value] || 0)
      const d21 = parseFloat(state.form[addTableData[19].value] || 0)
      const value = ((d21 / d4) * 100).toFixed(2)
      state.form['firstOverRateOfContractAmount'] = (isNaNOrInfinity(value) ? '0.00' : value) + '%'
    }

    // 新客合同金额首逾率
    function setNewFirstOverRateOfContractAmount() {
      const d5 = parseFloat(state.form[addTableData[3].value] || 0)
      const d22 = parseFloat(state.form[addTableData[20].value] || 0)
      const value = ((d22 / d5) * 100).toFixed(2)
      state.form['newFirstOverRateOfContractAmount'] = (isNaNOrInfinity(value) ? '0.00' : value) + '%'
    }

    // 老客合同金额首逾率
    function setOldFirstOverRateOfContractAmount() {
      const d6 = parseFloat(state.form[addTableData[4].value] || 0)
      const d23 = parseFloat(state.form[addTableData[21].value] || 0)
      const value = ((d23 / d6) * 100).toFixed(2)
      state.form['oldFirstOverRateOfContractAmount'] = (isNaNOrInfinity(value) ? '0.00' : value) + '%'
    }

    // 合同金额M1催回率
    function setContractAmountM1RateOfReminders() {
      const d21 = parseFloat(state.form[addTableData[19].value] || 0)
      const d27 = parseFloat(state.form[addTableData[25].value] || 0)
      const value = ((d27 / d21) * 100).toFixed(2)
      state.form['contractAmountM1RateOfReminders'] = (isNaNOrInfinity(value) ? '0.00' : value) + '%'
    }

    //收入合计
    function setTotalRevenue() {
      const d30 = parseFloat(state.form[addTableData[28].value] || 0)
      const d37 = parseFloat(state.form[addTableData[35].value] || 0)
      const d38 = parseFloat(state.form[addTableData[36].value] || 0)
      const value = (d30 + d37 + d38).toFixed(2)
      state.form['totalRevenue'] = (isNaNOrInfinity(value) ? '0.00' : value)
    }

    //主营业务收入合计
    function setTotalMainBusinessIncome() {
      let arrValue = []
      addTableData.forEach((item, index) => {
        if (index >= 29 && index <= 34) {
          const value = state.form[addTableData[index].value]
          if (value) {
            arrValue.push(parseFloat(value || 0))
          }
        }
      })
      state.form['totalMainBusinessIncome'] = arrValue.reduce(((previousValue, currentValue) => {
        return previousValue + currentValue
      })).toFixed(2)
    }

    //支出合计
    function setTotalExpenditure() {
      const d40 = parseFloat(state.form[addTableData[38].value] || 0)
      const d41 = parseFloat(state.form[addTableData[39].value] || 0)
      const d45 = parseFloat(state.form[addTableData[43].value] || 0)
      const d51 = parseFloat(state.form[addTableData[49].value] || 0)
      const value = (d40 + d41 + d45 + d51).toFixed(2)
      state.form['totalExpenditure'] = value || 0
    }

    //费用合计
    function setTotalCost() {
      let arrValue = []
      addTableData.forEach((item, index) => {
        if (index >= 40 && index <= 42) {
          const value = state.form[addTableData[index].value]
          if (value) {
            arrValue.push(parseFloat(value || 0))
          }
        }
      })
      state.form['totalCost'] = arrValue.reduce(((previousValue, currentValue) => {
        return previousValue + currentValue
      })).toFixed(2)
    }

    //资产减值损失合计
    function setTotalAssetImpairmentLoss() {
      let arrValue = []
      addTableData.forEach((item, index) => {
        if (index >= 44 && index <= 48) {
          const value = state.form[addTableData[index].value]
          if (value) {
            arrValue.push(parseFloat(value || 0))
          }
        }
      })
      state.form['totalAssetImpairmentLoss'] = arrValue.reduce(((previousValue, currentValue) => {
        return previousValue + currentValue
      })).toFixed(2)
    }

    function excelFileUpload(file) {
      let reader = new FileReader()
      reader.onload = async (e) => {
        let bstr = e.target.result;
        let wb = XLSX.read(bstr, {type: 'binary', cellDates: true});
        let wsname = wb.SheetNames[0];
        let ws = wb.Sheets[wsname];
        let data = XLSX.utils.sheet_to_json(ws, {header: 1});
        if (data.length > 0) {
          try {
            const dataValue = data.filter((item, index) => index !== 0)
            const keys = {}
            dataValue.forEach((item, index) => {
              if (item.length >= 4) {
                // 判断是否小数
                const isDecimal = item[3].toString().indexOf('.') > 0
                if (isDecimal) {
                  keys[addTableData[index].value] = item[3].toFixed(2)
                  if (item[3] < 1 && item[3] > 0) {
                    // 计算百分比
                    keys[addTableData[index].value] = (item[3] * 100).toFixed(2) + '%'
                  }
                } else {
                  keys[addTableData[index].value] = item[3]
                }
              }
            })
            state.form = {
              ...state.form,
              ...keys,
            }
            message.success('导入成功')
          } catch (e) {
            message.error('导入失败 ' + e)
          }
        }

      }
      reader.readAsBinaryString(file);
    }

    async function confirm() {
      if (!state.form.month) {
        return message.error('请选择月份')
      }
      const isAdd = state.visible.type === 'add'
      const api = (params) => isAdd ? increaseProfitAnalysis(params) : updateProfitAnalysis(params)
      const res = await api({
        ...state.form,
        businessId: parseInt(sessionStorage.getItem('businessValue'))
      })
      if (res.code === 200) {
        message.success(isAdd ? '添加成功' : '修改成功')
        getTableData()
        state.visible.isShow = false
      }
    }

    onMounted(() => {
      getTableData()
    })
    return {
      changeValueComputed,
      excelFileUpload,
      addTableData,
      addTableColumn,
      pagination,
      tableColumn,
      clearForm,
      confirm,
      addList,
      editList,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>

</style>
